/**
 * @file ext-chart.js
 *
 *
 * @copyright 2010 CloudCanvas, Inc. All rights reserved
 * @copyright 2021 Optimistik SAS, Inc. All rights reserved
 * @license MIT
 *
 */

const name = 'gaugechart'
const option = {
  title: {
    left: '45%',
    top: "1px",
    text: "仪表盘",
    textStyle: {
    }
},
  tooltip: {
    formatter: '{a} <br/>{b} : {c}%'
  },
  series: [
    {
      type: 'gauge',
      splitNumber: 10,
      axisLine: {
        lineStyle: {
          color: [
            [1, '#000']
          ]
        }
      },
      axisTick: {
        distance: -10,
        splitNumber: 5,
        show: true,
        inside:true ,
        lineStyle: {
          color: '#fff',
          width: 2
        }
      },
      splitLine: {
        lineStyle: {
          color: '#fff',
          width: 2
        },
        distance: -10,
      },
      axisLabel: {
        distance:10,
        color: 'inherit',
      },
      detail: {
        color: 'inherit'
      },
      data: [
        {
          value: 50,
          name: 'SCORE'
        }
      ]
    }
  ]
};
const loadExtensionTranslation = async function (svgEditor) {
  let translationModule
  const lang = svgEditor.configObj.pref('lang')
  try {
    translationModule = await import(`./locale/${lang}.js`)
  } catch (_error) {
    console.warn(`Missing translation (${lang}) for ${name} - using 'en'`)
    translationModule = await import('./locale/en.js')
  }
  svgEditor.i18next.addResourceBundle(lang, name, translationModule.default)
}
const initChart=function (container,option) {
  if (!option) {
    return;
  }
  $(container).empty()
  var chart = echarts.init(container, "macarons", {
    renderer: 'svg'
  });
  chart.setOption(option);
  return chart
}

export default {
  name,
  async init() {
    const svgEditor = this
    const { svgCanvas } = svgEditor
    const { ChangeElementCommand } = svgCanvas.history
    const addToHistory = (cmd) => { svgCanvas.undoMgr.addCommandToHistory(cmd) }
    const { $id, $click, $qq ,$} = svgCanvas
    let selElems
    let started
    let newFO
    let foreignObject
    let p = {}
    let charts = new Map()  
    await loadExtensionTranslation(svgEditor)
    /**
     *
     * @param {string} attr attribute to change
     * @param {string|Float} val new value
     * @returns {void}
     */
    const setAttr = (attr, val) => {
      svgCanvas.changeSelectedAttribute(attr, val)
      svgCanvas.call('changed', selElems)
    }
    
    return {
      name: svgEditor.i18next.t(`${name}:name`),
      // The callback should be used to load the DOM with the appropriate UI items
      callback() {
        // Add the button and its handler(s)
        // Note: the star extension needs to be loaded before the polygon extension
        const fbtitle = `${name}:title`
        const titleStar = `${name}:buttons.0.title`
        const titlePolygon = `${name}:buttons.1.title`
        const buttonTemplate = `
              <se-button id="tool_gaugechart" title="${titlePolygon}" src="gaugechart.svg">
              </se-button>
          `
        svgCanvas.insertChildAtIndex($qq('.shaps .itemWrap'), buttonTemplate, 17)

        $click($id('tool_gaugechart'), () => {
          if (this.leftPanel.updateLeftPanel('tool_gaugechart')) {
            svgCanvas.setMode('gaugechart')
          }
        })
      },
      mouseDown(opts) {
        if (svgCanvas.getMode() === 'gaugechart') {
          started = true
          //'x', 'y', 'r1', 'r2', 'angle', 'largeArcFlag', 'sweepFlag'
          p.x = opts.start_x
          p.y = opts.start_y
          var svgId = svgCanvas.getNextId()
          newFO = svgCanvas.addSVGElementsFromJson({
            element: 'g',
            attr: {
              class:'ems echart',
              id: svgId,
              'doc-type':'gaugechart'
            }
          })

          foreignObject = svgCanvas.addSVGElementsFromJson({
            element: 'foreignObject',
            attr: {
               x:p.x,
               y:p.y,
               width:350,
               height:310,
              class:'foreignObject_gauge',
              id:  "foreignObject" +svgId,
              'font-size': 12,
              'fill': "yellow",
              'text-anchor': 'middle',
              'xml:space': 'preserve',
              'stroke':'none',
              'opacity':1,
            }
          })
          newFO.append(foreignObject)
          var chart = initChart(document.getElementById(`foreignObject${svgId}`),option)
          charts.set(`foreignObject${svgId}`,chart)
          return {
            started: true
          }
        }
        return undefined
      },
      mouseMove(opts) {
        if (!started) {
          return undefined
        }
        var eles = svgCanvas.getSelectedElements()
        if (svgCanvas.getMode() === 'resize') {
          if(eles.length==1 && eles[0].classList.contains("gaugechart")){
            var chart = charts.get("foreignObject" +eles[0].id)
            if(chart){
              chart.resize()
            }
            return {
              started: true
            }
          }
        }
        return undefined
      },
      mouseUp() {
        if (svgCanvas.getMode() === 'resize' || svgCanvas.getMode() === 'select') {
          var eles = svgCanvas.getSelectedElements()
          if(eles.length>=1 && eles[0].classList.contains("echart")){
            var chart = charts.get("foreignObject" +eles[0].id)
            if(chart){
              chart.resize()
              return {
                started: false
              }
            }
          }
        }
        if (svgCanvas.getMode() === 'gaugechart') {
          const keep = true
          
          return {
            keep,
            element: newFO
          }
        }
        return undefined
      },
      sourceChanged(opts){
        let elem = opts.elems[0];
        if (!elem) return;
        if (elem.tagName === 'svg' && elem.id === 'svgcontent') {
          // Update svgContent (can change on import)
          var svgContent = elem;
          var foreignObjects =  $(svgContent).find(".foreignObject_gauge")
          Array.from(foreignObjects).forEach((elem, i) => {
            if(charts.get(elem.id)!=null){
              charts.get(elem.id).dispose()
              charts.delete(elem.id)
            }
            $(elem).removeAttr("_echarts_instance_")
            var chart = initChart(document.getElementById(elem.id),option)
            charts.set(elem.id,chart)
          })
        }
      },
      updategaugechart(opts){
        if(opts.mode !="gaugechart")return
        var data = opts.data
        var eles = svgCanvas.getSelectedElements()
        if (data.showtitle) {
            option.title.text = data.title
            option.title.textStyle.color = data.title_color
            option.title.textStyle.fontWeight = data?.fontSetValue?.cssstyle?.["font-weight"] || null
            option.title.textStyle.fontFamily = data?.fontSetValue?.cssstyle?.["fontfirst"] || null
            option.title.textStyle.fontSize = data?.fontSetValue?.cssstyle?.["font-size"] || null
            option.title.textStyle.fontStyle = data?.fontSetValue?.cssstyle?.["font-style"] || null
        }
        if(data.chartmin){
          option.series[0].min = data.chartmin
        }
        if(data.chartmax){
          option.series[0].max = data.chartmax
        }
        if(data.mainruler){
          option.series[0].splitNumber = data.mainruler
        }
        if(data.auxiliaryruler){
          option.series[0].axisTick.splitNumber = data.auxiliaryruler
        }
        charts.get(eles[0].firstChild.id).setOption(option, true);
        $(eles[0]).attr("requiredFeatures", btoa(unescape(encodeURIComponent(JSON.stringify(option)))))
        $(eles[0]).attr("state", btoa(unescape(encodeURIComponent(JSON.stringify(data)))))
        svgEditor.layersPanel.populateObjects()
        // addToHistory(new ChangeElementCommand(eles[0],{requiredFeatures:btoa(unescape(encodeURIComponent(JSON.stringify(option)))),state:btoa(unescape(encodeURIComponent(JSON.stringify(data))))}))
      }
    }
  }
}
